/*
 * @Description:
 * @version: 0.0.1
 * @Author: 小妖怪
 * @Date: 2021-07-27 21:14:04
 * @LastEditors: Mr.小妖怪
 * @LastEditTime: 2021-07-27 21:40:31
 * @FilePath: \study_typescript\demo\part3\index.ts
 */
{
  // 泛型
  // 不太好 使用 any 就关闭了 ts 的类型检查
  function fn(a: any): any {

  }

  /**
   * 在定义函数是类时，如果遇到类型不明确时就可以使用泛型
   */
  // 根据传递值得类型来判断返回类型
  let fn = function <T>(a: T): T {
    return a
  }

  let a = fn(10)
  let b = fn('hello wold')
  let r = fn<string>('my name is justin')

  let fn1 = function <T, K>(a: T, b: K): T {
    console.log(b)
    return a
  }

  interface Inter {
    length: number,
    [params: string]: any
  }

  // extends 表示泛型 T 必须是 Inter 接口的实现类
  let fn2 = function <T extends Inter>(a: T): number {
    return a.length
  }

  let o: Inter = {
    length: 3,
    name: 'justin',
    age: 22
  }

  let f = fn2<{ length: number }>(o)
  console.log(f);


  class MyClass<T>{
    name: T;
    constructor(name: T) {
      this.name = name
    }
    sayHi() {
      console.log('my name is ' + this.name)
    }
  }

  const cm = new MyClass<string>('justin')

  cm.sayHi()
}